<template>
  <div class="site-container">
    <!-- 左侧分类菜单 -->
    <div class="category-menu">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>站点分类</span>
          <el-button
            style="float: right; padding: 3px 0"
            type="text"
            @click="$router.push('/site/category')"
          >
            管理分类
          </el-button>
        </div>
        <el-menu
          :default-active="activeCategoryId"
          class="category-list"
          @select="handleCategorySelect"
        >
          <el-menu-item index="all">
            <i class="el-icon-menu"></i>
            <span>全部站点</span>
          </el-menu-item>
          <el-menu-item index="recommend">
            <i class="el-icon-star-on"></i>
            <span>推荐站点</span>
          </el-menu-item>
          <el-menu-item
            v-for="category in validCategories"
            :key="category.id"
            :index="String(category.id)"
          >
            <i :class="'el-icon-' + (category.categoryIcon || 'folder')"></i>
            <span>{{ category.categoryName }}</span>
          </el-menu-item>
        </el-menu>
      </el-card>
    </div>

    <!-- 右侧内容区 -->
    <div class="content-area">
      <el-card class="box-card">
        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-form :inline="true" :model="searchForm">
            <el-form-item>
              <el-input
                v-model="searchForm.siteName"
                placeholder="站点名称"
                clearable
                @keyup.enter.native="handleSearch"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button type="success" @click="handleAdd">新增站点</el-button>
              <el-button type="warning" @click="showImportDialog">
                <i class="el-icon-upload"></i> 导入收藏夹
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 站点卡片列表 -->
        <el-row :gutter="20">
          <el-col
            v-for="site in siteList"
            :key="site.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="4"
          >
            <el-card
              class="site-card"
              :body-style="{ padding: '0px' }"
              shadow="hover"
            >
              <div class="site-icon">
                <img :src="site.siteIcon || '/default-icon.png'" :alt="site.siteName">
              </div>
              <div class="site-info">
                <h3>{{ site.siteName }}</h3>
                <p>{{ site.description }}</p>
              </div>
              <div class="site-actions">
                <el-button type="text" @click="openSite(site.siteUrl)">访问</el-button>
                <el-button type="text" @click="handleEdit(site)">编辑</el-button>
                <el-button type="text" class="delete-btn" @click="handleDelete(site)">删除</el-button>
              </div>
              <div class="recommend-tag" v-if="site.isRecommend">
                <i class="el-icon-star-on"></i>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNo"
            :page-sizes="[12, 24, 48, 96]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          />
        </div>

        <!-- 导入收藏夹对话框 -->
        <el-dialog title="导入收藏夹" :visible.sync="importDialogVisible" width="500px">
          <el-form :model="importForm" label-width="100px">
            <el-form-item label="浏览器类型">
              <el-select v-model="importForm.browserType" placeholder="请选择浏览器类型">
                <el-option label="Chrome/Edge" value="chrome"></el-option>
                <el-option label="Firefox" value="firefox"></el-option>
                <el-option label="Safari" value="safari"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="收藏夹文件">
              <el-upload
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :on-change="handleFileChange"
                :file-list="fileList"
                :limit="1">
                <el-button size="small" type="primary">选择文件</el-button>
                <div slot="tip" class="el-upload__tip">
                  支持HTML/JSON格式的收藏夹文件
                </div>
              </el-upload>
            </el-form-item>
            
            <el-form-item label="自动分类">
              <el-switch v-model="importForm.autoCategory"></el-switch>
            </el-form-item>
          </el-form>
          
          <div slot="footer" class="dialog-footer">
            <el-button @click="importDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleImport" :loading="importing">
              开始导入
            </el-button>
          </div>
        </el-dialog>
      </el-card>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="站点名称" prop="siteName">
          <el-input v-model="form.siteName" />
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.categoryName"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="站点地址" prop="siteUrl">
          <el-input v-model="form.siteUrl" />
        </el-form-item>
        <el-form-item label="站点图标" prop="siteIcon">
          <el-input v-model="form.siteIcon" placeholder="请输入图标URL" />
        </el-form-item>
        <el-form-item label="站点描述" prop="description">
          <el-input type="textarea" v-model="form.description" />
        </el-form-item>
        <el-form-item label="是否推荐" prop="isRecommend">
          <el-switch v-model="form.isRecommend" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllCategories,
  getSiteList,
  getSitesByCategory,
  getRecommendSites,
  addSite,
  updateSite,
  deleteSite,
  updateSiteRecommend,
  importBookmarks
} from '@/api/site'

export default {
  name: 'Site',
  data() {
    return {
      // 分类列表
      categories: [],
      activeCategoryId: 'all',
      // 搜索表单
      searchForm: {
        siteName: ''
      },
      // 分页参数
      pageNo: 1,
      pageSize: 12,
      total: 0,
      // 数据列表
      siteList: [],
      loading: false,
      // 对话框
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        categoryId: null,
        siteName: '',
        siteUrl: '',
        siteIcon: '',
        description: '',
        isRecommend: false,
        sortOrder: 0
      },
      // 表单校验规则
      rules: {
        siteName: [
          { required: true, message: '请输入站点名称', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择所属分类', trigger: 'change' }
        ],
        siteUrl: [
          { required: true, message: '请输入站点地址', trigger: 'blur' },
          { type: 'url', message: '请输入正确的URL地址', trigger: 'blur' }
        ],
        sortOrder: [
          { required: true, message: '请输入排序号', trigger: 'blur' }
        ]
      },
      // 导入相关
      importDialogVisible: false,
      importing: false,
      importForm: {
        browserType: 'chrome',
        autoCategory: true
      },
      fileList: []
    }
  },
  computed: {
    validCategories() {
      return this.categories.filter(category => category && category.id != null)
    }
  },
  created() {
    this.fetchCategories()
    this.fetchSites()
  },
  methods: {
    // 获取分类列表
    async fetchCategories() {
      try {
        const res = await getAllCategories()
        if (res.data && res.data.code === 20000) {
          this.categories = res.data.data || []
        } else {
          this.categories = []
        }
        console.log('分类数据:', this.categories) // 添加调试日志
      } catch (error) {
        console.error('获取分类列表失败:', error)
        this.$message.error('获取分类列表失败')
        this.categories = []
      }
    },
    // 获取站点列表
    async fetchSites() {
      this.loading = true
      try {
        let res
        if (this.activeCategoryId === 'all') {
          res = await getSiteList({
            pageNo: this.pageNo,
            pageSize: this.pageSize,
            siteName: this.searchForm.siteName
          })
          if (res.data && res.data.code === 20000) {
            this.siteList = res.data.data.rows || []
            this.total = res.data.data.total || 0
          } else {
            this.siteList = []
            this.total = 0
          }
        } else if (this.activeCategoryId === 'recommend') {
          res = await getRecommendSites()
          if (res.data && res.data.code === 20000) {
            this.siteList = res.data.data || []
            this.total = (res.data.data || []).length
          } else {
            this.siteList = []
            this.total = 0
          }
        } else {
          res = await getSitesByCategory(this.activeCategoryId)
          if (res.data && res.data.code === 20000) {
            this.siteList = res.data.data || []
            this.total = (res.data.data || []).length
          } else {
            this.siteList = []
            this.total = 0
          }
        }
        console.log('站点列表数据:', this.siteList) // 添加调试日志
      } catch (error) {
        console.error('获取站点列表失败:', error)
        this.$message.error('获取站点列表失败')
        this.siteList = []
        this.total = 0
      }
      this.loading = false
    },
    // 选择分类
    handleCategorySelect(index) {
      this.activeCategoryId = index
      this.pageNo = 1
      this.fetchSites()
    },
    // 搜索
    handleSearch() {
      this.pageNo = 1
      this.fetchSites()
    },
    // 新增
    handleAdd() {
      this.dialogTitle = '新增站点'
      this.form = {
        id: null,
        categoryId: null,
        siteName: '',
        siteUrl: '',
        siteIcon: '',
        description: '',
        isRecommend: false,
        sortOrder: 0
      }
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑站点'
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该站点吗？', '提示', {
        type: 'warning'
      })
        .then(async () => {
          try {
            await deleteSite(row.id)
            this.$message.success('删除成功')
            this.fetchSites()
          } catch (error) {
            console.error('删除站点失败:', error)
            this.$message.error('删除站点失败')
          }
        })
        .catch(() => {})
    },
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            if (this.form.id) {
              await updateSite(this.form)
              this.$message.success('修改成功')
            } else {
              await addSite(this.form)
              this.$message.success('新增成功')
            }
            this.dialogVisible = false
            this.fetchSites()
          } catch (error) {
            console.error('保存站点失败:', error)
            this.$message.error('保存站点失败')
          }
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchSites()
    },
    handleCurrentChange(val) {
      this.pageNo = val
      this.fetchSites()
    },
    // 打开站点
    openSite(url) {
      window.open(url, '_blank')
    },
    // 显示导入对话框
    showImportDialog() {
      this.importDialogVisible = true
      this.fileList = []
      this.importForm = {
        browserType: 'chrome',
        autoCategory: true
      }
    },
    // 处理文件选择
    handleFileChange(file) {
      this.fileList = [file]
    },
    // 处理导入
    async handleImport() {
      if (this.fileList.length === 0) {
        this.$message.warning('请选择收藏夹文件')
        return
      }
      
      this.importing = true
      try {
        const formData = new FormData()
        formData.append('file', this.fileList[0].raw)
        formData.append('browserType', this.importForm.browserType)
        formData.append('autoCategory', this.importForm.autoCategory)
        
        const res = await importBookmarks(formData)
        if (res.data.code === 20000) {
          this.$message.success('导入成功')
          this.importDialogVisible = false
          this.fetchSites() // 刷新站点列表
        } else {
          this.$message.error(res.data.message || '导入失败')
        }
      } catch (error) {
        console.error('导入失败:', error)
        this.$message.error('导入失败：' + (error.message || '未知错误'))
      } finally {
        this.importing = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.site-container {
  display: flex;
  gap: 20px;
  min-height: calc(100vh - 84px);
  
  .category-menu {
    width: 240px;
    flex-shrink: 0;
    
    .category-list {
      border-right: none;
    }
  }
  
  .content-area {
    flex: 1;
    
    .search-bar {
      margin-bottom: 20px;
    }
  }
}

.site-card {
  margin-bottom: 20px;
  position: relative;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
  }

  .site-icon {
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
    padding: 20px;
    
    img {
      max-width: 80px;
      max-height: 80px;
      object-fit: contain;
    }
  }

  .site-info {
    padding: 14px;
    min-height: 120px;
    
    h3 {
      margin: 0 0 10px;
      font-size: 16px;
      font-weight: 500;
      color: #303133;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    p {
      margin: 0;
      font-size: 13px;
      color: #909399;
      line-height: 1.5;
      height: 60px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
    }
  }

  .site-actions {
    padding: 10px 14px;
    border-top: 1px solid #ebeef5;
    text-align: right;
    background: #f5f7fa;
    
    .el-button {
      padding: 0 10px;
      font-size: 13px;
      
      & + .el-button {
        margin-left: 10px;
      }
    }
    
    .delete-btn {
      color: #f56c6c;
    }
  }

  .recommend-tag {
    position: absolute;
    top: 10px;
    right: 10px;
    color: #e6a23c;
    font-size: 20px;
  }
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.box-card {
  height: 100%;
}

.upload-demo {
  width: 100%;
}
</style> 